package session1.examples.lock;

import java.util.Scanner;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Eg4 {
	static class DataShare{
		static int d=0,MAX=500;
		private static final ReentrantLock myLock;
		private static final Condition waitCondition;
		static{
			myLock=new ReentrantLock();
			waitCondition= myLock.newCondition();
		}
		public static void consume(int amount){
			myLock.lock();
			try{
				while(d<amount){
					System.out.printf("现在有%d,需要量为%d\n",d,amount);
					waitCondition.wait();
				}
				d-=amount;
				System.out.printf("消费者——消耗了%d，剩余量：%d\n",amount,d);
			}catch (InterruptedException e){
				System.out.println(e.getMessage());
			}catch (IllegalMonitorStateException e){
				System.out.println("**生产者占用**");
			}
			finally {	myLock.unlock();	}
		}
		public static void produce(){
			myLock.lock();
			try{
				while(d>MAX){
					System.out.printf("现在有%d,已超过最大库存量%d，我先歇会\n",d,MAX);
					waitCondition.wait();
				}
				d+=100;
				System.out.printf("生产者——剩余量：%d\n",d);
			}catch (InterruptedException e){
				System.out.println(e.getMessage());
			}catch (IllegalMonitorStateException e){
				System.out.println("**消费者占用**");
			}
			finally {	myLock.unlock();	}
		}
	}

	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		System.out.println("输入任意字符开始");
		scanner.nextLine();
		new Producer().start();
		new Consumer().start();
		scanner.nextLine();
		System.out.println("**强制退出**");
		System.exit(0);
	}
}
class Producer extends Thread{
	@Override
	public void run() {
		while (true){
			Eg4.DataShare.produce();
			try {Thread.sleep(500);}
			catch (InterruptedException e)
			{System.out.println(e.getMessage());}
		}
	}
}
class Consumer extends Thread{
	@Override
	public void run() {
		while (true){
			Eg4.DataShare.consume((int) (Math.random()*100));
			try {Thread.sleep(Eg4.DataShare.MAX);}
			catch (InterruptedException e)
			{System.out.println(e.getMessage());}
		}
	}
}
